package com.theorydance.esoperator.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import org.apache.commons.lang.StringUtils;
import net.sf.json.JSONObject;

public class FSTools {
	
	/**
	 * 把参数body中的数据放到httppost请求的body中
	 */
    public static String httpPost(String httpUrl, Map<String,String> body) {
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(2000);
			conn.setReadTimeout(5000);
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			OutputStream output = conn.getOutputStream();
			JSONObject json = JSONObject.fromObject(body);
			output.write(json.toString().getBytes());
			InputStream input = null;
			if(conn.getContentEncoding().toLowerCase().contains("gzip")) {
				input = new GZIPInputStream(conn.getInputStream()); 
			}else {
				input = conn.getInputStream();
			}
			System.out.println(conn.getContentType());
			System.out.println(conn.getHeaderField("X-Powered-By"));
			StringBuffer sb = new StringBuffer();
			int len = 0;
			byte[] buf = new byte[1024];
			while((len=input.read(buf))!=-1) {
				sb.append(new String(buf, 0, len, Tools.UTF8));
			}
			input.close();
			return sb.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    /**
     * 将参数params中的数据拼接到请求地址上
     */
	public static String httpGet(String httpUrl, Map<String,String> params){
		if(params == null || params.size() == 0) {
			return httpGet(httpUrl);
		}
		String paramstr = "";
		for (String key : params.keySet()) {
			paramstr += "&" + key + "=" + params.get(key);
		}
		if(httpUrl.contains("?")) {
			return httpGet(httpUrl + paramstr);
		}else {
			return httpGet(httpUrl + "?" + paramstr.substring(1));
		}
	}
	
	public static String httpGet(String httpUrl){
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(2000);
			conn.setReadTimeout(5000);
			conn.connect();
			InputStream input = conn.getInputStream();
			int len = 0;
			byte[] buf = new byte[1024];
			StringBuffer sb = new StringBuffer();
			while((len=input.read(buf))!=-1) {
				sb.append(new String(buf, 0, len,Tools.UTF8));
			}
			input.close();
			return sb.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 加法
	 */
	public static BigDecimal calc_add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2);
    }

	/**
	 * 减法
	 */
    public static BigDecimal calc_sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2);
    }

    /**
	 * 乘法
	 */
    public static BigDecimal calc_mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2);
    }

    /**
     * v1/v2的值，四舍六入5留双，默认无小数
     */
    public static BigDecimal calc_div(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, 0, BigDecimal.ROUND_HALF_EVEN);
    }

    /**
     * 返回v1/v2的值、四舍六入5留双、指定小数位数
     */
    public static BigDecimal calc_div_scale(double v1, double v2, int scale) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_EVEN);
    }

    /**
	 * 提供精确的小数位四舍五入处理。
	 *
	 * @param v     需要四舍五入的数字
	 * @param scale 小数点后保留几位
	 * @return 四舍五入后的结果
	 */
	public static double calc_round(double v, int scale) {
	    if (scale < 0) {
	        throw new IllegalArgumentException("The scale must be a positive integer or zero");
	    }
	    BigDecimal b = new BigDecimal(Double.toString(v));
	    BigDecimal one = new BigDecimal("1");
	    return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 提供精确的格式化小数位四舍五入处理。
	 *
	 * @param v      需要四舍五入的数字
	 * @param scale  小数点后保留几位
	 * @param Format 输出的格式 如保留小数点后2位"#.00"
	 * @return 四舍五入后的格式化结果
	 */
	public static String calc_round(double v, int scale, String Format) {
	    if (scale < 0) {
	        throw new IllegalArgumentException("The scale must be a positive integer or zero");
	    }
	    BigDecimal b = new BigDecimal(Double.toString(v));
	    BigDecimal one = new BigDecimal("1");
	    DecimalFormat df1 = new DecimalFormat(Format);
	    return df1.format(b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue());
	}

	/**
	 * 提供精确的格式化小数位处理。
	 *
	 * @param v      需要四舍五入的数字
	 * @param Format 输出的格式 如保留小数点后2位"#.00"
	 * @return 四舍五入后的格式化结果
	 */
	public static String calc_round(double v, String Format) {
	    DecimalFormat df1 = new DecimalFormat(Format);
	    return df1.format(v);
	}

	/**
	 * 获取小数后进行截取位数
	 *
	 * @param val 值
	 * @param num 小数点后保留的位数
	 * @return
	 */
	public static double calc_getDecimal(Double val, int num) {
	    if (val == null) {
	        return 0;
	    }
	    BigDecimal b = new BigDecimal(val);
	    return b.setScale(num, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * @param value 需要科学计算的数据
	 * @param digit 保留的小数位
	 * @return 功能：四舍六入五成双计算法
	 */
	public static double calc_sciCal(double value, int digit) {
	    String result = "-999";
	    try {
	        double ratio = Math.pow(10, digit);
	        double _num = value * ratio;
	        double mod = _num % 1;
	        double integer = Math.floor(_num);
	        double returnNum;
	        if (mod > 0.5) {
	            returnNum = (integer + 1) / ratio;
	        } else if (mod < 0.5) {
	            returnNum = integer / ratio;
	        } else {
	            returnNum = (integer % 2 == 0 ? integer : integer + 1) / ratio;
	        }
	        BigDecimal bg = new BigDecimal(returnNum);
	        result = bg.setScale((int) digit, BigDecimal.ROUND_HALF_UP).toString();
	    } catch (RuntimeException e) {
	        throw e;
	    }
	    double dou = Double.parseDouble(result);
	    return dou;
	}

	public static String date_getYesterday() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(calendar.getTime());
    }

    public static String date_formatDate(java.util.Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    public static String date_formatDate(java.util.Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 通过1年中的周数，获取指定周的起止时间（包含起，不包含止）
     *
     * @param week
     * @return
     */
    public static Map<String, String> date_getStartAndEndTimeByWeek(int week, int year) {
        Map<String, String> map = new HashMap<String, String>();
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        c.set(Calendar.YEAR, year);
        c.set(Calendar.WEEK_OF_YEAR, week);
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        String startTIme = sdf.format(c.getTime());
        c.add(Calendar.DAY_OF_YEAR, 7);
        String endTime = sdf.format(c.getTime());
        map.put("startTime", startTIme);
        map.put("endTime", endTime);
        return map;
    }

    /**
     * 获取当前周的起止时间（包含起，不包含止）
     *
     * @return
     */
    public static Map<String, String> date_getStartAndEndTimeByWeek() {
        Map<String, String> map = new HashMap<String, String>();
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // c.set(Calendar.YEAR, year);
        // c.set(Calendar.WEEK_OF_YEAR, week);
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        String startTIme = sdf.format(c.getTime());
        c.add(Calendar.DAY_OF_YEAR, 7);
        String endTime = sdf.format(c.getTime());
        map.put("startTime", startTIme);
        map.put("endTime", endTime);
        return map;
    }

    /**
     * 获取时间的分段区间 （按天）
     *
     * @param beginTime
     * @param endTime
     * @param num       份数
     * @return
     */
    public static String[] date_getdates(String beginTime, String endTime, int num) {
        String[] dates = new String[num];

        long days = date_getDiffDay(beginTime, endTime);
        int fen = (int) days / num;
        int lastFen = (int) (fen + days % num);

        String curtime = date_getNowDate();
        for (int i = 0; i < num; i++) {
            if (i == num - 1) {
                dates[i] = date_getDate(curtime, 1, lastFen);
            } else {
                dates[i] = date_getDate(curtime, 1, fen);
            }
            curtime = dates[i];
        }
        return dates;
    }

    /**
     * 时间的加减运算
     *
     * @param time 起始时间
     * @param type 类型
     * @param num  数量
     * @return
     */
    public static String date_getDate(String time, int type, int num) {
        String resTime = "";
        try {
            // 字符串时间转Date
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            java.util.Date d = sdf.parse(time);

            Calendar c = Calendar.getInstance();

            // Date 转Calendar
            c.setTime(d);

            // 使用Calendar 进行时间的加减运算
            if (type == 2) {
                c.add(Calendar.MONTH, num);
            } else if (type == 1) {
                c.add(Calendar.DATE, num);
            } else if (type == 3) {
                c.add(Calendar.YEAR, num);
            } else if (type == 4) {
                c.add(Calendar.HOUR, num);
            } else if (type == 5) {
                c.add(Calendar.MINUTE, num);
            } else if (type == 6) {
                c.add(Calendar.SECOND, num);
            }

            // 最终把Calendar 转Date 再转 String 输出
            resTime = sdf.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resTime;
    }

    public static String date_getDate(String time, String format, int type, int num) {
        String resTime = "";
        try {
            // 字符串时间转Date
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            java.util.Date d = sdf.parse(time);

            Calendar c = Calendar.getInstance();

            // Date 转Calendar
            c.setTime(d);

            // 使用Calendar 进行时间的加减运算
            if (type == 2) {
                c.add(Calendar.MONTH, num);
            } else if (type == 1) {
                c.add(Calendar.DATE, num);
            } else if (type == 3) {
                c.add(Calendar.YEAR, num);
            } else if (type == 4) {
                c.add(Calendar.HOUR_OF_DAY, num);
            }

            // 最终把Calendar 转Date 再转 String 输出
            resTime = sdf.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resTime;
    }

    /**
     * 获取日期相差天数
     *
     * @param
     * @return 日期类型时间
     * @throws java.text.ParseException
     */
    public static int date_getDiffDay(String beginDate, String endDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int checkday = 0; // 开始结束相差天数
        try {
            checkday = (int) ((formatter.parse(endDate).getTime() - formatter.parse(beginDate).getTime())
                    / (1000 * 24 * 60 * 60));
            Long temp = (formatter.parse(endDate).getTime() - formatter.parse(beginDate).getTime())
                    % (1000 * 24 * 60 * 60);
            if (temp > 0) {
                checkday += 1;
            } else if (temp < 0) {
                checkday -= 1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            checkday = 0;
        }
        return checkday;
    }

    public static int date_getDiffDay(java.util.Date beginDate, java.util.Date endDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strBeginDate = format.format(beginDate);
        String strEndDate = format.format(endDate);
        return date_getDiffDay(strBeginDate, strEndDate);
    }

    public static Long date_getDiffMinutes(String beginDate, String endDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long check = 0l; // 开始结束相差天数
        try {
            check = (formatter.parse(endDate).getTime() - formatter.parse(beginDate).getTime()) / (1000 * 60);
        } catch (ParseException e) {
            e.printStackTrace();
            check = null;
        }
        return check;
    }

    /**
     * 获取字符串 对应的 毫秒时间
     *
     * @param time
     * @return
     */
    public static Long date_dateStrToLong(String time) {
        if (time.length() == 10) {
            time = time + " 00:00:00";
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long check = 0l;
        try {
            check = formatter.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            check = null;
        }
        return check;
    }

    public static Long date_getDiffMinutes(java.util.Date beginDate, java.util.Date endDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strBeginDate = format.format(beginDate);
        String strEndDate = format.format(endDate);
        return date_getDiffMinutes(strBeginDate, strEndDate);
    }

    public static String date_getNowDate() {
	    SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Calendar now = Calendar.getInstance();
	    return s.format(now.getTime()).toString();
	}

	public static String date_getNowDate(String format) {
	    SimpleDateFormat s = new SimpleDateFormat(format);
	    Calendar now = Calendar.getInstance();
	    return s.format(now.getTime()).toString();
	}

	public static String date_getDate(String m) {
	    if (m == null)
	        return date_getNowDate();
	    m = m.trim();
	    if (m.equals(""))
	        return date_getNowDate();
	    try {
	        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
	        m = s.format(s.parse(m)).toString();
	    } catch (Exception e) {
	        m = date_getNowDate();
	    }
	    return m;
	}

	/**
	 * date 转换为时间串
	 */
	public static String date_getDateString(java.util.Date date) {
	    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String str = format.format(date);
	    return str;
	}

	public static String date_getDateString(java.util.Date date, String format) {
	    SimpleDateFormat sdf = new SimpleDateFormat(format);
	    String str = sdf.format(date);
	    return str;
	}

	public static String date_timeOperate(String time, String format, int type, int num, int position, int length) {
	    String res = null;
	    String outFormat = "yyyy-MM-dd HH:mm:ss:SSS";
	    try {
	        SimpleDateFormat inSdf = new SimpleDateFormat(format);
	        SimpleDateFormat outSdf = new SimpleDateFormat(outFormat);
	        Calendar c = Calendar.getInstance();
	        c.setTime(inSdf.parse(time));
	        c.add(type, num);
	        res = outSdf.format(c.getTime()).substring(position, length);
	    } catch (ParseException e) {
	        e.printStackTrace();
	    }
	    return res;
	}

	/**
     * 返回普通sql日期
     *
     * @param dates
     * @return
     */
    public static Date date_getSqlDate(String dates) {
        Date sqlDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            java.util.Date date = sdf.parse(dates);
            sqlDate = new Date(date.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlDate;
    }

    /**
     * 返回当前精确sql日期
     *
     * @return
     */
    public static Timestamp date_getSqlTime() {
        Timestamp sqlDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            java.util.Date date = sdf.parse(date_getNowDate("yyyy-MM-dd hh:mm:ss"));
            sqlDate = new Timestamp(date.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlDate;
    }

    /**
	 * 创建一个时间，这个时间根据 cf : Calendar的格式 n ： 创建的时间的增量，正数加，负数减
	 */
	public static String date_createTime(int cf, int n) {
	    Calendar c = Calendar.getInstance();
	    c.add(cf, n);
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String mDateTime = formatter.format(c.getTime());
	    return mDateTime;
	}

	/**
	 * 根据起止时间，获取在时间段内的时间集合
	 *
	 * @param start    开始时间（包含）
	 * @param end      截止（包含）
	 * @param timeType 使用Calendar中的值
	 * @return
	 */
	public static List<String> date_getLostTime(String start, String end, int timeType) {
	    List<String> list = new ArrayList<String>();
	    String format = null;
	    switch (timeType) {
	        case Calendar.HOUR_OF_DAY:
	            format = "yyyy-MM-dd HH";
	            break;
	        case Calendar.DAY_OF_MONTH:
	            format = "yyyy-MM-dd";
	            break;
	        case Calendar.MONTH:
	            format = "yyyy-MM";
	            break;
	        default:
	            return list;
	    }
	    try {
	        SimpleDateFormat sdf = new SimpleDateFormat(format);
	        Calendar cursor = Calendar.getInstance();
	        Calendar cEnd = Calendar.getInstance();
	        cEnd.setTime(sdf.parse(end));
	        cursor.setTime(sdf.parse(start));
	        while (cursor.getTimeInMillis() <= cEnd.getTimeInMillis()) {
	            list.add(sdf.format(cursor.getTime()));
	            cursor.add(timeType, 1);
	        }
	    } catch (ParseException e) {
	        e.printStackTrace();
	    }
	    return list;
	}

	/**
	 * 获取分钟数整的当前时间
	 *
	 * @param date
	 * @param string
	 */
	public static String date_getDataMinute(java.util.Date date, String string) {
	    SimpleDateFormat sdf = new SimpleDateFormat(string);
	    String format = sdf.format(date);
	    String substring = format.substring(0, 15);
	    substring = substring + "0";
	    return substring;
	}

	/**
	 * 得到去年和今年的所有月份
	 *
	 * @return
	 */
	public static List<String> date_getMonths() {
	    List<String> list = new ArrayList<String>();
	    try {
	        Calendar c = Calendar.getInstance();
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
	        String nowMonth = sdf.format(c.getTime());
	
	        int lastYear = c.get(Calendar.YEAR) - 1;
	        nowMonth = (lastYear + 1) + "-12";
	        java.util.Date date = sdf.parse(lastYear + "-01");
	        c.setTime(date);
	        int num = 30;
	        while (num-- > 0) {
	            String cursor = sdf.format(c.getTime());
	            list.add(cursor);
	            if (cursor.equals(nowMonth)) {
	                break;
	            }
	            c.add(Calendar.MONTH, 1);
	        }
	
	    } catch (ParseException e) {
	        e.printStackTrace();
	    }
	    return list;
	}

	public static List<String> date_getMonths(String start, String end) {
	    List<String> list = new ArrayList<String>();
	    Calendar cursor = Calendar.getInstance();
	    Calendar endPoint = Calendar.getInstance();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
	    int n = 30; // 避免循环次数过多陷入死循环
	    try {
	        String startMonth = start.substring(0, 7);
	        String endMonth = end.substring(0, 7);
	        cursor.setTime(sdf.parse(startMonth));
	        endPoint.setTime(sdf.parse(endMonth));
	        do {
	            list.add(sdf.format(cursor.getTime()));
	            cursor.add(Calendar.MONTH, 1);
	            if (cursor.getTimeInMillis() <= endPoint.getTimeInMillis()
	                    || sdf.format(cursor.getTime()).equals(sdf.format(endPoint.getTime()))) {
	
	            } else {
	                break;
	            }
	            if (--n < 0) {
	                break;
	            }
	        } while (true);
	    } catch (ParseException e) {
	        e.printStackTrace();
	    }
	    return list;
	}

	/**
	 * @param formatstr    需要转换的格式
	 * @param sdataeformat 日期本来的格式
	 * @param sdate        日期字符串
	 * @return
	 * @throws java.text.ParseException
	 */
	public static String date_formatedate(String formatstr, String sdataeformat, String sdate) throws ParseException {
	    java.util.Date date = null;
	    SimpleDateFormat bartDateFormat = new SimpleDateFormat(sdataeformat);
	    date = bartDateFormat.parse(sdate);
	    SimpleDateFormat formatter1 = new SimpleDateFormat(formatstr);
	    String timems = formatter1.format(date);
	    return timems;
	}

	public static Date date_parseTimeStr(String time, String format) throws Exception {
	    SimpleDateFormat sdf = new SimpleDateFormat(format);
	    return sdf.parse(time);
	}

	/**
	 * 
	* @Title: getNowDate
	* @Description: (获取系统实时时间，格式由调用者传入)
	* @return String    返回类型
	 */
	public static String date_getNowDate(String time, String format,String type, int num) {
		String format2 = null;
		try {
			SimpleDateFormat sf = new SimpleDateFormat(format);
			Calendar cal = Calendar.getInstance();
			if(!"null".equals(time+"") && time!=""){
				 java.util.Date d = sf.parse(time);
				 cal.setTime(d);
			}
			if(type!=null){
			     //使用Calendar  进行时间的加减运算
				if (type.equals("SECOND")) {
					cal.add(Calendar.SECOND, num);
				} else if (type.equals("MINUTE")) {
					cal.add(Calendar.MINUTE, num);
				} else if (type.equals("HOUR")) {
					cal.add(Calendar.HOUR, num);
				} else if (type.equals("DAY")) {
					cal.add(Calendar.DAY_OF_MONTH, num);
				} else if (type.equals("MONTH")) {
					cal.add(Calendar.MONTH, num);
				} else if (type.equals("YEAR")) {
					cal.add(Calendar.YEAR, num);
				}
			}
	        Date time2 = cal.getTime();
			format2 = sf.format(time2).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return format2;
	}

	/**
	 * @Description: (设置系统实时时间，格式由调用者传入)
	 * @return String    返回类型
	 */
	public static String date_setDate(String time, String format, String type, int num){
		String format2 = null;
		try {
			SimpleDateFormat sf = new SimpleDateFormat(format);
			Calendar cal = Calendar.getInstance();
			if(StringUtils.isNotEmpty(time)){
				 java.util.Date d = sf.parse(time);
				 cal.setTime(d);
			}/*else{
				String d2 = sf.format(new Date());
				cal.setTime(sf.parse(d2));
			}*/
			if(type!=null){
			     //使用Calendar  进行时间的加减运算
				if (type.equals("SECOND")) {
					cal.set(Calendar.SECOND, num);
				} else if (type.equals("MINUTE")) {
					cal.set(Calendar.MINUTE, num);
				} else if (type.equals("HOUR")) {
					cal.set(Calendar.HOUR_OF_DAY, num);
				} else if (type.equals("DATE")) {
					cal.set(Calendar.DAY_OF_MONTH, num);
				} else if (type.equals("MONTH")) {
					cal.set(Calendar.MONTH, num);
				} else if (type.equals("YEAR")) {
	            	cal.set(Calendar.YEAR, num);
	            }
			}
	        Date time2 = cal.getTime();
			format2 = sf.format(time2).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return format2;
	}

	/**
	 * 
	 * @Title: getTimeDifference
	 * @Description: (小时数据获取判定)
	 * @param    设定文件
	 * @return String    返回类型
	 */
	public static int date_getTimeDifference(String stime,String etime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date1=new Date();
		Date date2=new Date();
		try {
			date1 = format.parse(etime);
			date2 = format.parse(stime);
		} catch (ParseException e) {
			e.printStackTrace();
		}	
		return (int) ((date1.getTime() - date2.getTime()) / (1000*3600*24));
	}

	/**
	 * 获取某一年的所有月份
	 * @param year
	 * @return
	 */
	public static List<String> date_getMonths(String year){
		 String[] months= {"01","02","03","04","05","06","07","08","09","10","11","12"};
		 List<String> list = Stream.of(months).map(x -> year+"-"+x).collect(Collectors.toList());
		 return list;
	}

	/**
	 * 返回两个时间的之间的集合
	 */
	public static List<String> date_getDates(String type,String sdate,String edate) throws Exception{
		String timeFrom="";
		Long oneDay=null;
		if(type=="HOUR") {
			timeFrom="yyyy-MM-dd HH";
			oneDay= 1000 * 60 * 60 * 1l;  
		}
		if(type=="DAY") {
			timeFrom="yyyy-MM-dd";
			oneDay = 1000 * 60 * 60 * 24l;  
		}
		
		DateFormat df_ = new SimpleDateFormat(timeFrom);
		Date startDate = df_.parse(sdate);
		
		Date endDate = df_.parse(edate);
		
		Calendar start = Calendar.getInstance();  
	    start.setTime(startDate); 
	    Long startTIme = start.getTimeInMillis(); 
	    
	    List<String> list=new ArrayList<>();
	    
	    
	    Calendar end = Calendar.getInstance();  
	    end.setTime(endDate);  
	    Long endTime = end.getTimeInMillis();  
	
	
	    Long time = startTIme;  
	    while (time <= endTime) {  
	        Date d = new Date(time);  
	        DateFormat df = new SimpleDateFormat(timeFrom);  
	        list.add(df.format(d));
	        time += oneDay;  
	    }  
	    
	    return list;
	}

	public static String date_getWeekStartDay() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_WEEK, 1);
		c.add(Calendar.DAY_OF_MONTH, 1);
		return sdf.format(c.getTime());
	}

	public static boolean date_isLocalWeek(String time) {
		String stime = date_getWeekStartDay();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		boolean res = false;
		try {
			res = sdf.parse(time).getTime() >= sdf.parse(stime).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return res;
	}

	public static boolean date_isLocalMonth(String time) {
		String month = new SimpleDateFormat("yyyy-MM").format(new Date());
		return time.startsWith(month);
	}

	/**
	 * 根据起止时间，填充缺失时间对应的数据
	 * @param list 需要填充的集合，要求list中至少有一个对象
	 * @param timeName 时间名称
	 * @param stime 开始时间（包含）
	 * @param etime 结束时间（包含）
	 * @param dim 时间维度，Calendar相关
	 * @return 填充的个数
	 */
	public static List<Map<String,Object>> date_fillListByTime(List<? extends Map<String, Object>> list, String timeName, String stime, String etime,
			int dim) {
		// 存放返回结果
		List<Map<String,Object>> resList = new ArrayList<>();
		// 1、获取需要填充的属性
		Set<String> attrs = new HashSet<>();
		list.stream().map(Map::keySet).forEach(attrs::addAll);
		
		// 2、遍历list，判断是否含有指定的时间，如果不含有就追加
		if(Calendar.HOUR_OF_DAY == dim) {
			try {
				List<String> times = date_getDates("HOUR", stime, etime);
				for (String time : times) {
					Map<String, Object> record = null;
					for (Map<String, Object> map : list) {
						// 遍历追加到resList中
						String timeV = (String) map.get(timeName);
						if(time.equals(timeV)) {
							record = map;
							break;
						}
					}
					if(record == null) {
						record = new HashMap<>();
						for (String attr : attrs) {
							record.put(attr, null);
						}
						record.put(timeName, time);
					}
					resList.add(record);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(Calendar.DAY_OF_MONTH == dim) {
			
		}
		return resList;
	}

	/**
	 * 四舍六入5留双
	 */
	public static double format_objTodouble(Double data, int scale) {
	    if (data == null)
	        return 0;
	    return BigDecimal.valueOf(data).setScale(BigDecimal.ROUND_HALF_EVEN, scale).doubleValue();
	}

	public static Double format_objToDouble(Object obj) {
	    return obj != null && !"".equals(obj) ? Double.parseDouble(obj.toString()) : null;
	}

	public static double format_objTodouble(Object obj) {
	    return obj != null && !"".equals(obj) ? Double.parseDouble(obj.toString()) : 0.0;
	}

	/**
	 * 转换成INT
	 *
	 * @param obj
	 * @return
	 */
	public static Integer format_objToInt(Object obj) {
	    return obj != null && !"".equals(obj) ? Integer.parseInt(new DecimalFormat("0").format(format_objToDouble(obj.toString()))) : null;
	}

	public static int format_objToint(Object obj) {
	    return obj != null && !"".equals(obj) ? Integer.parseInt(new DecimalFormat("0").format(format_objToDouble(obj.toString()))) : 0;
	}

	public static <T> T format_transferBaseObject(Object obj, Class<T> clazz) throws Exception {
	    if (obj == null) {
	        throw new ClassCastException();
	    }
	    Class tempClazz = obj.getClass();
	    if (tempClazz == clazz) {
	        return (T) obj;
	    }
	    String objStr = obj.toString();
	    if (clazz == String.class) {
	        return (T) objStr;
	    } else if (clazz == Integer.class) {
	        return (T) Integer.valueOf(objStr);
	    } else if (clazz == Long.class) {
	        return (T) Long.valueOf(objStr);
	    } else if (clazz == Float.class) {
	        return (T) Float.valueOf(objStr);
	    } else if (clazz == Double.class) {
	        return (T) Double.valueOf(objStr);
	    } else {
	        throw new Exception("is not base wrapper.");
	    }
	}

	public static String format_fillEmpty(String str) {
	    if (str == null || str.equals("")) {
	        return "";
	    }
	    return str;
	}

	public static int format_fillEmpty(Integer obj) {
	    if (obj == null) {
	        return 0;
	    }
	    return obj;
	}

	public static long format_fillEmpty(Long obj) {
	    if (obj == null) {
	        return 0L;
	    }
	    return obj;
	}

	public static double format_fillEmpty(Double obj) {
	    if (obj == null) {
	        return 0.0;
	    }
	    return obj;
	}

	public static String format_getChnMoney(String bigdMoneyNumber) {
        return format_getChnMoney(new BigDecimal(bigdMoneyNumber));
    }

    public static String format_getChnMoney(BigDecimal bigdMoneyNumber) {
        String[] straChineseUnit = new String[]{"分", "角", "圆", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰",
                "仟"};
        String[] straChineseNumber = new String[]{"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};// 中文数字字符数组
        String strChineseCurrency = "";
        boolean bZero = true;// 零数位标记
        int ChineseUnitIndex = 0;// 中文金额单位下标
        try {
            if (bigdMoneyNumber.intValue() == 0)
                return "零圆整";
            double doubMoneyNumber = Math.round(bigdMoneyNumber.doubleValue() * 100);// 处理小数部分，四舍五入
            boolean bNegative = doubMoneyNumber < 0;// 是否负数
            doubMoneyNumber = Math.abs(doubMoneyNumber);// 取绝对值
            while (doubMoneyNumber > 0)// 循环处理转换操作
            {
                if (ChineseUnitIndex == 2 && strChineseCurrency.length() == 0)
                    strChineseCurrency = strChineseCurrency + "整";// 整的处理(无小数位)
                if (doubMoneyNumber % 10 > 0)// 非零数位的处理
                {
                    strChineseCurrency = straChineseNumber[(int) doubMoneyNumber % 10]
                            + straChineseUnit[ChineseUnitIndex] + strChineseCurrency;
                    bZero = false;
                } else {// 零数位的处理
                    if (ChineseUnitIndex == 2)// 元的处理(个位)
                    {
                        if (doubMoneyNumber > 0)// 段中有数字
                        {
                            strChineseCurrency = straChineseUnit[ChineseUnitIndex] + strChineseCurrency;
                            bZero = true;
                        }
                    } else if (ChineseUnitIndex == 6 || ChineseUnitIndex == 10)// 万、亿数位的处理
                    {
                        if (doubMoneyNumber % 1000 > 0)
                            strChineseCurrency = straChineseUnit[ChineseUnitIndex] + strChineseCurrency;// 段中有数字
                    }
                    if (!bZero)
                        strChineseCurrency = straChineseNumber[0] + strChineseCurrency; // 前一数位非零的处理
                    bZero = true;
                }
                doubMoneyNumber = Math.floor(doubMoneyNumber / 10);
                ChineseUnitIndex++;
            }
            if (bNegative)
                strChineseCurrency = "负" + strChineseCurrency;// 负数的处理
        } catch (Exception e) {
            return "";
        }
        return strChineseCurrency;
    }

    public static String format_getChinese(String s) {
        if (s == null)
            return "";
        try {
            String convert = new String(s.getBytes("ISO8859_1"), "GB2312");
            return convert;
        } catch (Exception e) {
        }
        return s;
    }

    public static String format_getCharset(String s, String fromCharset1, String toCharset2) {
        if (s == null)
            return "";
        try {
            String convert = new String(s.getBytes(fromCharset1), toCharset2);
            return convert;
        } catch (Exception e) {
        }
        return s;
    }
	
	/**
	 * 获取百分数
	 *
	 * @param size
	 * @param count
	 * @return
	 */
	public static String format_getPercent(int size, int count) {
	    int num1 = size;
	    int num2 = count;
	    // 创建一个数值格式化对象
	    NumberFormat numberFormat = NumberFormat.getInstance();
	    // 设置精确到小数点后2位
	    numberFormat.setMaximumFractionDigits(2);
	    String result = numberFormat.format((float) num1 / (float) num2 * 100);
	    System.out.println("num1和num2的百分比为:" + result + "%");
	    return result + "%";
	}

	// 返回给定的字符长度
    // s:要截取的字符串
    // LimitStrlen:长度
    // IsReturnSpace:当s为null时是否返回" ";为true:要返回；false：不返回
    // IsDouHao:返回值中是否将字符串中的上逗号'去掉 为true:要去掉；false：不去掉
//    public static String getSaveStr(String s){boolean m;if(DBConnect.Ver==0)m=false;else m=true;return getLimitLenStr(s,0,m,true);}
//    public static String getSaveStr(String s,int LimitStrlen){boolean m;if(DBConnect.Ver==0)m=false;else m=true;return getLimitLenStr(s,LimitStrlen,m,true);}
    public static String format_getLimitLenStr(String s, int LimitStrlen) {
        return format_getLimitLenStr(s, LimitStrlen, false);
    }

    public static String format_getLimitLenStr(String s, int LimitStrlen, boolean IsReturnSpace) {
        return format_getLimitLenStr(s, LimitStrlen, IsReturnSpace, false);
    }

    public static String format_getLimitLenStr(String s, int LimitStrlen, boolean IsReturnSpace, boolean IsDouHao) {
        if (s == null)
            if (IsReturnSpace == true)
                return " ";
            else
                return "";
        s = s.replace("'", "");
        if (LimitStrlen != 0) {
            char[] cc = s.toCharArray();
            int intLen = 0;
            int i;
            // if("中国".length()==4){return s.substring(Maxlen/2);}
            for (i = 0; i < cc.length; i++) {
                if ((int) cc[i] > 255) {
                    intLen = intLen + 2;
                } else {
                    intLen++;
                }
                if (intLen >= LimitStrlen) {
                    break;
                }
            }
            if (intLen == LimitStrlen)
                i++;
            s = s.substring(0, i);
        }
        if (s.equals(""))
            if (IsReturnSpace == true)
                return s = " ";
        if (IsDouHao == true)
            s = s.replace("'", "");
        return s;
    }

    public static String format_getLimitChinese(String s, int MaxLen) {
        if (s == null)
            return "";
        try {
            String convert = new String(s.getBytes("ISO8859_1"), "GB2312");
            convert = format_getLimitLenStr(convert, MaxLen);
            // String convert=getLimitLenStr(s,MaxLen);
            return convert;
        } catch (Exception e) {
        }
        return "";
    }

    /**
	 * 将小数保留指定的位数
	 * @param value 需要格式化的小数
	 * @param bit 需要保留的小数位数
	 * @return
	 */
	public static Double format_formatDouble(Double value, int bit) {
		if (value == null) {
			return null;
		}
		return (int)(value*Math.pow(10, bit))/Math.pow(10.0, bit);
	}

}
